import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Table, Tag, Progress, Spin } from 'antd';
import { 
  ShoppingCartOutlined, 
  BarChartOutlined, 
  DollarCircleOutlined,
  BoxPlotOutlined,
  TrophyOutlined,
  FireOutlined 
} from '@ant-design/icons';
import { getProductStatistics, type ProductStatistics } from '@/services/products';

const ProductStatisticsPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [statistics, setStatistics] = useState<ProductStatistics | null>(null);

  // 类别表格列配置
  const categoryColumns = [
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: '产品数量',
      dataIndex: 'product_count',
      key: 'product_count',
      render: (count: number) => (
        <Tag color="blue">{count}</Tag>
      ),
    },
    {
      title: '平均价格',
      dataIndex: 'avg_price',
      key: 'avg_price',
      render: (price: any) => {
        const numPrice = typeof price === 'number' ? price : parseFloat(price) || 0;
        return `¥${numPrice.toFixed(2)}`;
      },
    },
    {
      title: '总销量',
      dataIndex: 'total_sales',
      key: 'total_sales',
      render: (sales: number) => (
        <Tag color="green">{sales}</Tag>
      ),
    },
  ];

  // 品牌表格列配置
  const brandColumns = [
    {
      title: '品牌',
      dataIndex: 'brand',
      key: 'brand',
    },
    {
      title: '产品数量',
      dataIndex: 'product_count',
      key: 'product_count',
      render: (count: number) => (
        <Tag color="blue">{count}</Tag>
      ),
    },
    {
      title: '平均价格',
      dataIndex: 'avg_price',
      key: 'avg_price',
      render: (price: any) => {
        const numPrice = typeof price === 'number' ? price : parseFloat(price) || 0;
        return `¥${numPrice.toFixed(2)}`;
      },
    },
    {
      title: '总销量',
      dataIndex: 'total_sales',
      key: 'total_sales',
      render: (sales: number) => (
        <Tag color="green">{sales}</Tag>
      ),
    },
  ];

  // 价格区间表格列配置
  const priceRangeColumns = [
    {
      title: '价格区间',
      dataIndex: 'price_range',
      key: 'price_range',
    },
    {
      title: '产品数量',
      dataIndex: 'product_count',
      key: 'product_count',
      render: (count: number) => (
        <Tag color="blue">{count}</Tag>
      ),
    },
    {
      title: '占比',
      key: 'percentage',
      render: (record: any) => {
        const total = statistics?.priceRanges.reduce((sum, item) => sum + item.product_count, 0) || 1;
        const percentage = ((record.product_count / total) * 100).toFixed(1);
        return (
          <div style={{ width: 120 }}>
            <Progress 
              percent={parseFloat(percentage)} 
              size="small" 
              format={() => `${percentage}%`}
            />
          </div>
        );
      },
    },
  ];

  // 获取统计数据
  const fetchData = async () => {
    try {
      setLoading(true);
      const data = await getProductStatistics();
      setStatistics(data);
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  if (loading) {
    return (
      <div className="p-6 flex justify-center items-center" style={{ minHeight: '400px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!statistics) {
    return (
      <div className="p-6 flex justify-center items-center" style={{ minHeight: '400px' }}>
        <div className="text-gray-500">暂无统计数据</div>
      </div>
    );
  }

  return (
    <div className="p-6">
      <div className="mb-4">
        <h2 className="text-xl font-semibold flex items-center">
          <BarChartOutlined className="mr-2" />
          产品统计概览
        </h2>
      </div>

      {/* 总览统计卡片 */}
      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总产品数"
              value={statistics.products.total_products}
              prefix={<ShoppingCartOutlined />}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="有效产品"
              value={statistics.products.active_products}
              prefix={<BoxPlotOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="平均价格"
              value={typeof statistics.products.avg_price === 'number' ? statistics.products.avg_price : parseFloat(statistics.products.avg_price) || 0}
              prefix={<DollarCircleOutlined />}
              precision={2}
              suffix="元"
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总销量"
              value={statistics.products.total_sales}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 产品状态统计 */}
      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="库存不足"
              value={statistics.products.out_of_stock}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="库存偏低"
              value={statistics.products.low_stock}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="特色产品"
              value={statistics.products.featured_products}
              prefix={<TrophyOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card size="small">
            <Statistic
              title="热门产品"
              value={statistics.products.hot_products}
              prefix={<FireOutlined />}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 配置统计 */}
      <Row gutter={[16, 16]} className="mb-6">
        <Col xs={24} md={8}>
          <Card size="small" title="配置统计">
            <Statistic
              title="总配置数"
              value={statistics.configs.total_configs}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card size="small">
            <Statistic
              title="平均配置价格"
              value={typeof statistics.configs.avg_config_price === 'number' ? statistics.configs.avg_config_price : parseFloat(statistics.configs.avg_config_price) || 0}
              precision={2}
              suffix="元"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} md={8}>
          <Card size="small">
            <Statistic
              title="平均性能评分"
              value={typeof statistics.configs.avg_performance_score === 'number' ? statistics.configs.avg_performance_score : parseFloat(statistics.configs.avg_performance_score) || 0}
              precision={1}
              suffix="分"
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 详细统计表格 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <Card title="类别统计" size="small">
            <Table
              columns={categoryColumns}
              dataSource={statistics.categories}
              rowKey="category"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="品牌统计" size="small">
            <Table
              columns={brandColumns}
              dataSource={statistics.brands}
              rowKey="brand"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} className="mt-4">
        <Col xs={24}>
          <Card title="价格区间分布" size="small">
            <Table
              columns={priceRangeColumns}
              dataSource={statistics.priceRanges}
              rowKey="price_range"
              pagination={false}
              size="small"
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default ProductStatisticsPage; 